package com.kgc.springboot.hangduo.controller;

import com.kgc.springboot.hangduo.pojo.User;
import com.kgc.springboot.hangduo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

/**
 * @author: ASUS
 * @date: 2020/12/22 20:35
 * @description:
 */
@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/userlogin")
    public String userLogin(String phone, String password, HttpSession session, Model model){
        User user = userService.login(phone, password);
        if(user!=null){
            user.setLoginTime(new Date());
            InetAddress localHost = null;
            try {
                localHost = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            String hostAddress = localHost.getHostAddress();
            user.setIp(hostAddress);
            userService.updateByUser(user);
            session.setAttribute("user",user);
            return "my";
        }else {
            model.addAttribute("msg","用户名或密码错误，请重新登录！！！");
            return "login";
        }
    }
    @RequestMapping("/userSaveRemark")
    @ResponseBody
    public String userSaveRemark(Integer userid,String remark,HttpSession session){
        User user = userService.selectById(userid);
        user.setRemark(remark);
        int i = userService.updateByUser(user);
        if(i>0){
            session.setAttribute("user",user);
            return "1";
        }else {
            return "0";
        }

    }
    @RequestMapping("/savePassword")
    @ResponseBody
    public String savePassword(String pass,String OrdPass,HttpSession session){
        User user = (User) session.getAttribute("user");
        if(user.getPassword().equals(OrdPass)){
            user.setPassword(pass);
            int i = userService.updateByUser(user);
            if(i>0){
                session.setAttribute("user",user);
                return "1";
            }else {
                return "0";
            }
        } else {
            return "2";
        }

    }

}
